import { Controller, Get, Post, HttpException, Param, Render, Res, Body } from '@nestjs/common';
import { AppService } from './app.service';
import { WebSocketServer } from '@nestjs/websockets';
import { Server } from 'socket.io';
import socketClientStore, { ClientEvent } from './events/socket.client.store';
import { Response } from 'express';
import { BusinessException } from './common/business.exceptions';
import { BusinessErrorCode } from './common/business.error.code';

@Controller()
export class AppController {
  @WebSocketServer()
  server: Server;
  
  constructor(private readonly appService: AppService) {}

  @Get()
  @Render('index')
  root() {
    return { message: 'Hello world!', clients: socketClientStore.getList() };
    // return res.render(
    //   'index',
    //   { message: 'xxxxxxxxxx' }
    // )
  }

  @Get("/client/:id/reload")
  reload(@Param() params: any):any{
    const clientWrap = socketClientStore.getById(params.id);
    if(!clientWrap){
      throw new BusinessException(`client is not exsits! id: [${params.id}]`, BusinessErrorCode.CLIENT_NOT_EXISTS);
    }
    clientWrap.client.emit('events', { action: 'reload' });
    clientWrap.client.emit('events', JSON.stringify({ action: 'reload' }));
    clientWrap.client.emit('reload', { action: 'reload' });
    return { status: 200, message: 'OK'}
  }

  @Post("/client/:id/event")
  postEvent(@Param() params: any, @Body() event: ClientEvent):any{
    const clientWrap = socketClientStore.getById(params.id);
    if(!clientWrap){
      throw new BusinessException(`client is not exsits! id: [${params.id}]`, BusinessErrorCode.CLIENT_NOT_EXISTS);
    }
    clientWrap.client.emit('events', event);
    return { status: 200, message: 'OK', data: event}
  }

  @Get()
  getHello(): string {
    console.log(socketClientStore.getList());
    socketClientStore.getList().forEach(item=>{
      item.client.emit('events', { name: 'Nest111' });
    })
    return socketClientStore.getList().map(item=>{
      return JSON.stringify({
        id: item.client.id,
        address: item.address
      })
    }).join('\n')
    // return this.appService.getHello();
  }
}
